package com.activenetwork.util;

import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


/**
 * Strategy to user pool. <br/>
 * In concurrency situation, when a request comes, all the users may already be
 * used by other tests. In this case, this request will have to wait until some
 * other test case release an user.
 */
public class UserPoolStrategy implements UserStrategy {

    private final BlockingQueue<String[]> usersPool = new LinkedBlockingQueue<String[]>();
    public UserPoolStrategy (Collection<String[]> users)
    {
        usersPool.addAll(users);
    }   

    public String[] get() {
        String[] usernameAndPassword = EnvContext.userTL.get();
        if (usernameAndPassword == null) {
            try {
                usernameAndPassword = usersPool.take();
            } catch (InterruptedException e) {
                throw new RuntimeException(
                        "InterruptedException happened when tries to get user name and password.");
            }
            EnvContext.userTL.set(usernameAndPassword);
        }
        return usernameAndPassword;
    }

    public void release() {
        String[] usernameAndPassword = EnvContext.userTL.get();
        if(usernameAndPassword!=null)
        {
            usersPool.add(usernameAndPassword);
            EnvContext.userTL.set(null);
        }else{
        	System.out.println("release user failed or script is not using userTL");
        }
    }
}
